package com.cpit.qualitycontrol.service.impl;

import com.cpit.platform.common.constant.SystemConstant;
import com.cpit.platform.common.entity.TableDataQueryCondition;
import com.cpit.platform.security.service.UserInfo;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Created by Hull on 2017/10/10.
 * Service专用工具类
 */
public class ServiceUtils {
    /**
     * 通过TableDataQueryCondition获取PageRequest对象，用于构造分页查询条件
     * @param cond TableDataQueryCondition对象
     * @return PageRequest对象
     */
    public static PageRequest getPageRequestByTableDataQueryCondition(TableDataQueryCondition cond) {
        if (cond == null) {
            return null;
        }

        if(cond.getSidx() == null || cond.getSidx().length() == 0) {
            cond.setSidx("id");
        }

        Sort.Direction der;
        if(cond.getSord() == null || cond.getSord().length() == 0) {
            der = Sort.Direction.ASC;
        } else {
            der = cond.getSord().equals(SystemConstant.DIRECTION_ASC) ? Sort.Direction.ASC : Sort.Direction.DESC;
        }

        return new PageRequest(cond.getPageNumber() - 1, cond.getRowsNumber(), new Sort(der, cond.getSidx()));
    }
    /**
     * 获取登录用户信息
     *
     * @return
     */
    public static  UserInfo getLoginUser() {
        UserInfo userDetails = (UserInfo) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();

        return userDetails;
    }
}
